package com.oa.om.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.query.QueryTools;
import com.mdp.core.utils.RequestUtils;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import com.oa.om.entity.OmAppliance;
import com.oa.om.entity.OmCategory;
import com.oa.om.service.OmApplianceService;
import com.oa.om.service.OmCategoryService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@RestController
@RequestMapping(value = "/**/oa/om/omCategory")
@Api(tags = {"办公用品分类-操作接口"})
public class OmCategoryController {

    static Logger logger = LoggerFactory.getLogger(OmCategoryController.class);

    @Autowired
    private OmCategoryService omCategoryService;

    @Autowired
    private OmApplianceService omApplianceService;

    @ApiOperation(value = "办公用品分类-查询列表", notes = " ")
    @ApiEntityParams(OmCategory.class)
    @ApiResponses({@ApiResponse(code = 200, response = OmCategory.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result listOmCategory(@ApiIgnore @RequestParam Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        QueryWrapper<OmCategory> qw = QueryTools.initQueryWrapper(OmCategory.class, params);
        IPage page = QueryTools.initPage(params);
        RequestUtils.transformArray(params, "ids");
        List<Map<String, Object>> datas = omCategoryService.selectListMapByWhere(page, qw, params);
        return Result.ok("query-ok", "查询成功").setData(datas).setTotal(page.getTotal());
    }

    @ApiOperation(value = "查询om_appliance及分类下的信息", notes = "getAllOmAppliance,条件之间是 and关系,模糊查询写法如 {studentName:'%才哥%'}")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "主键,主键", required = false), @ApiImplicitParam(name = "name", value = "名称", required = false), @ApiImplicitParam(name = "status", value = "状态1启用0禁用", required = false), @ApiImplicitParam(name = "branchId", value = "机构号", required = false), @ApiImplicitParam(name = "remark", value = "备注说明", required = false), @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false), @ApiImplicitParam(name = "currentPage", value = "当前页码,从1开始", required = false), @ApiImplicitParam(name = "total", value = "总记录数,服务器端收到0时，会自动计算总记录数，如果上传>0的不自动计算", required = false), @ApiImplicitParam(name = "orderFields", value = "排序列 如性别、学生编号排序 ['sex','studentId']", required = false), @ApiImplicitParam(name = "orderDirs", value = "排序方式,与orderFields对应，升序 asc,降序desc 如 性别 升序、学生编号降序 ['asc','desc']", required = false)})
    @ApiResponses({@ApiResponse(code = 200, response = OmCategory.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},pageInfo:{total:总记录数},data:[数据对象1,数据对象2,...]}")})
    @RequestMapping(value = "/getAllOmAppliance", method = RequestMethod.GET)
    public Result getAllOmAppliance(@RequestParam Map<String, Object> omCategory) {
        Map<String, Object> m = new HashMap<>();
        QueryWrapper<OmCategory> qw = QueryTools.initQueryWrapper(OmCategory.class, omCategory);
        IPage page = QueryTools.initPage(omCategory);
        User user = LoginUtils.getCurrentUserInfo();
        omCategory.put("branchId", user.getBranchId());
        List<Map<String, Object>> omCategoryList = omCategoryService.selectListMapByWhere(page, qw, omCategory);
        OmAppliance omAppliance = new OmAppliance();
        omAppliance.setBranchId(user.getBranchId());
        List<Map<String, Object>> omAppliances = omApplianceService.selectAllSimpleAppliance(user.getBranchId());//列出OmCategory列表
        Map<String, List<Map<String, Object>>> childrenMap = new HashMap<>();
        for (Map<String, Object> appliance : omAppliances) {
            String categoryId = (String) appliance.get("categoryId");
            List<Map<String, Object>> children = childrenMap.get(categoryId);
            if (children == null) {
                children = new ArrayList<>();
            }
            children.add(appliance);
            childrenMap.put(categoryId, children);
        }
        List<Map> results = new ArrayList<>();
        if (!omCategoryList.isEmpty()) {
            omCategoryList.forEach((cate) -> {
                String categoryId = (String) cate.get("id");
                List<Map<String, Object>> children = childrenMap.get(categoryId);
                Map<String, Object> result = new HashMap<>();
                result.put("name", cate.get("name"));
                result.put("categoryId", categoryId);
                result.put("children", children);
                results.add(result);
            });
        }
        return Result.ok().setData(results);
    }


    @ApiOperation(value = "办公用品分类-新增", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = OmCategory.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result addOmCategory(@RequestBody OmCategory omCategory) {
        if (StringUtils.isEmpty(omCategory.getId())) {
            omCategory.setId(omCategoryService.createKey("id"));
        } else {
            OmCategory omCategoryQuery = new OmCategory(omCategory.getId());
            if (omCategoryService.countByWhere(omCategoryQuery) > 0) {
                return Result.error("编号重复，请修改编号再提交");
            }
        }
        omCategoryService.insert(omCategory);
        return Result.ok("add-ok", "添加成功！").setData(omCategory);
    }

    @ApiOperation(value = "办公用品分类-删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")})
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delOmCategory(@RequestBody OmCategory omCategory) {
        omCategoryService.deleteByPk(omCategory);
        return Result.ok("del-ok", "删除成功！");
    }

    @ApiOperation(value = "办公用品分类-修改", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = OmCategory.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result editOmCategory(@RequestBody OmCategory omCategory) {
        omCategoryService.updateByPk(omCategory);
        return Result.ok("edit-ok", "修改成功！").setData(omCategory);
    }

    @ApiOperation(value = "办公用品分类-批量修改某些字段", notes = "")
    @ApiEntityParams(value = OmCategory.class, props = {}, remark = "办公用品分类", paramType = "body")
    @ApiResponses({@ApiResponse(code = 200, response = OmCategory.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/editSomeFields", method = RequestMethod.POST)
    public Result editSomeFields(@ApiIgnore @RequestBody Map<String, Object> params) {
        User user = LoginUtils.getCurrentUserInfo();
        omCategoryService.editSomeFields(params);
        return Result.ok("edit-ok", "更新成功");
    }

    @ApiOperation(value = "办公用品分类-批量删除", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")})
    @RequestMapping(value = "/batchDel", method = RequestMethod.POST)
    public Result batchDelOmCategory(@RequestBody List<OmCategory> omCategorys) {
        User user = LoginUtils.getCurrentUserInfo();
        if (omCategorys.size() <= 0) {
            return Result.error("batchDel-data-err-0", "请上送待删除数据列表");
        }
        List<OmCategory> datasDb = omCategoryService.listByIds(omCategorys.stream().map(i -> i.getId()).collect(Collectors.toList()));
        List<OmCategory> can = new ArrayList<>();
        List<OmCategory> no = new ArrayList<>();
        for (OmCategory data : datasDb) {
            if (true) {
                can.add(data);
            } else {
                no.add(data);
            }
        }
        List<String> msgs = new ArrayList<>();
        if (can.size() > 0) {
            omCategoryService.removeByIds(can);
            msgs.add(LangTips.transMsg("del-ok-num", "成功删除%s条数据.", can.size()));
        }
        if (no.size() > 0) {
            msgs.add(LangTips.transMsg("not-allow-del-num", "以下%s条数据不能删除:【%s】", no.size(), no.stream().map(i -> i.getId()).collect(Collectors.joining(","))));
        }
        if (can.size() > 0) {
            return Result.ok(msgs.stream().collect(Collectors.joining()));
        } else {
            return Result.error(msgs.stream().collect(Collectors.joining()));
        }
    }

    @ApiOperation(value = "办公用品分类-根据主键查询一条数据", notes = " ")
    @ApiResponses({@ApiResponse(code = 200, response = OmCategory.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")})
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result queryById(OmCategory omCategory) {
        OmCategory data = (OmCategory) omCategoryService.getById(omCategory);
        return Result.ok().setData(data);
    }

}
